﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace SequenceAssembler
{
    public class Reader: IDisposable
    {
        private TextReader inFile;

        public Reader(int initIdMinus1 = 0) {
			CurrentID = initIdMinus1;
			CurrentRead = null;
		}

        public void Open(string filename) {
            inFile = new StreamReader(filename);
        }

		public void Close() {
			if (null != inFile) {
				inFile.Close();
			}
		}

        public bool Next() {
			if (null == inFile.ReadLine())
			{
				return false;
			}
			string read = inFile.ReadLine();
			if (read == null)
			{
				CurrentRead = null;
				return false;
			} else {
                read = read.Replace("N", "A");
				CurrentRead = read;
			}
			++CurrentID;
			// reverse fix for inward fa file
			if ((CurrentID & 1) == 0) //even
			{
				CurrentRead = BaseOperation.reverseComplement(CurrentRead);
			}
			return true;
        }

        public string CurrentRead { get; set; }

		/// <summary>
		/// Starting from 1.
		/// </summary>
        public int CurrentID { get; set;}
    
        public void  Dispose()
        {
 	        Close();
        }

		public static void unitTest()
		{
			using (Reader reader = new Reader())
			{
				reader.Open("../../../data/test_reads.fa");
				while (reader.Next())
				{
					int seqid = reader.CurrentID;
					string seq = reader.CurrentRead;
					Console.Write(seqid);
					Console.Write('\t');
					Console.WriteLine(seq);
				}
			}
		}
    }
}
